package com.zhentao.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.jwt.JWT;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhentao.common.Result;
import com.zhentao.domain.SysUser;
import com.zhentao.domain.dto.LoginDto;
import com.zhentao.domain.dto.PageDto;
import com.zhentao.domain.vo.UserVo;
import com.zhentao.service.SysUserService;
import com.zhentao.mapper.SysUserMapper;
import com.zhentao.util.JwtService;
import com.zhentao.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
* @author 86133
* @description 针对表【sys_user】的数据库操作Service实现
* @createDate 2024-08-20 17:17:50
*/
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
    implements SysUserService{
    @Autowired
    private StringRedisTemplate redis;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public Result login(LoginDto loginDto) {
        if (Objects.isNull(loginDto))return Result.build(null, 500, "参数为空");
        if (StringUtils.checkValNull(loginDto.getUsername())||StringUtils.checkValNull(loginDto.getPassword())) return Result.build(null, 500, "请检查");
        SysUser user = this.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, loginDto.getUsername()));
        if (Objects.isNull(user))return Result.build(null, 500, "账号不存在");
        String userPassword = DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes());
        if(!user.getPassword().equals(userPassword))return Result.build(null, 500, "密码错误");
        UUID uuid = UUID.randomUUID();
        String token = uuid.toString().replace("-", "");
        redis.opsForValue().set("login:token:"+token, JSON.toJSONString(user),30, TimeUnit.MINUTES);
        return Result.build(token, 200, "登录成功");
    }

    @Override
    public Result getUserInfo() {
        SysUser sysUser = ThreadLocalUtil.get();
        return Result.build(sysUser, 200, "获取成功");
    }

    @Override
    public Result addUser(LoginDto loginDto) {
        if(loginDto==null)return Result.build(null,500,"参数为空");
        if(StringUtils.checkValNull(loginDto.getUsername())||StringUtils.checkValNull(loginDto.getPassword())||StringUtils.checkValNull(loginDto.getRePassword()))return Result.build(null,500,"请检查");
        if(!loginDto.getPassword().equals(loginDto.getRePassword()))return Result.build(null,500,"两次密码不一致");
        SysUser sysUser = this.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, loginDto.getUsername()));
        if (BeanUtil.isNotEmpty(sysUser))return Result.build(null,500,"用户已存在");
        SysUser user = new SysUser();
        user.setUsername(loginDto.getUsername());
        user.setPassword(DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes()));
        boolean save = this.save(user);
        return save?Result.build(null,200,"注册成功"):Result.build(null,500,"注册失败");
    }
    //    用户站点查询分页
    @Override
    public PageInfo<SysUser> getUserList(PageDto pageDto) {
        PageHelper.startPage(pageDto.getPage(),pageDto.getSize());
        List<SysUser> list = sysUserMapper.list();
        PageInfo<SysUser> sysUserPageInfo = new PageInfo<>(list);
        return sysUserPageInfo;

    }

    @Override
    public int add(String phone) {
        return sysUserMapper.add(phone);
    }

    @Override
    public int delete(Integer id) {
        return sysUserMapper.delete(id);
    }

    @Override
    public int update(SysUser sysUser) {
        return sysUserMapper.update(sysUser);
    }

    @Override
    public Result getAllUsers() {
        List<String> range1 = redis.opsForList().range("login:data:seven", 0, 6);
        range1.add(String.valueOf(this.list().size()));
        return Result.build(range1, 200, "查询成功");
    }



    public void getUserData(){
        List<String> range = redis.opsForList().range("login:data:seven", 0, 6);
        Map<Object, Object> data = redis.opsForHash().entries("login:data");
        Set<Object> set = data.keySet();
        Date date = new Date();
        StringBuilder sb = new StringBuilder();
        int hours = date.getHours();
        int minutes = date.getMinutes();
        sb.append(hours).append(":").append(minutes);
        UserVo userVo = new UserVo();
        userVo.setDate(String.valueOf(sb));
        userVo.setNum(set.size());
        //获取集合中的元素判断是否大于7，如果大于7，左删除，在右添加到redis当中
        if(range.size()==7){
            redis.opsForList().leftPop("login:data:seven");
            redis.opsForList().rightPush("login:data:seven", JSON.toJSONString(userVo));
        }else{
            redis.opsForList().rightPush("login:data:seven", JSON.toJSONString(userVo));
        }
    }

    @Scheduled(cron = "0 0/5 * * * ? ")
//    @Scheduled(cron ="0/3 * * * * ? ")
    public void test(){
        getUserData();
        System.out.println("定时任务执行了");
    }
}




